package com.jiazhong.example.project.bookstore.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiazhong.example.project.bookstore.backend.service.CategoryService;
import com.jiazhong.example.project.bookstore.commons.bean.Book;
import com.jiazhong.example.project.bookstore.commons.bean.Category;
import com.jiazhong.example.project.bookstore.commons.handler.CategoryRemoveException;
import com.jiazhong.example.project.bookstore.commons.mapper.BookMapper;
import com.jiazhong.example.project.bookstore.commons.mapper.CategoryMapper;
import com.jiazhong.example.project.bookstore.commons.util.JsonResult;
import com.jiazhong.example.project.bookstore.commons.util.ResultTool;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private BookMapper bookMapper;

    @Override
    public JsonResult find() {
        return ResultTool.success(list());
    }
    public JsonResult removeByCategoryId1(String categoryId) {
        boolean b1 = removeById(categoryId);
        if (!b1) {
            throw new CategoryRemoveException("删除分类失败");
        }
        return ResultTool.success("success");
    }
    @Transactional(rollbackFor = {SQLException.class, CategoryRemoveException.class})
    public JsonResult removeByCategoryId2(String categoryId) {
        // 1. 删除分类
        boolean b1 = removeById(categoryId);
        if (!b1) {
            throw new CategoryRemoveException("删除分类失败");
        }
        // 2. 更新图书，将图书中的分类设置为null
        UpdateWrapper<Book> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("category_id", categoryId);
        updateWrapper.set("category_id", null);
        int b2 = bookMapper.update(updateWrapper);
        if (b2 == 0) {
            throw new CategoryRemoveException("删除分类失败");
        }
        return ResultTool.success("success");
    }
}
